package com.xxxx.yoyo.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xxxx.yoyo.bean.Goods;
import com.xxxx.yoyo.bean.Type;
import com.xxxx.yoyo.service.IGoodsService;
import com.xxxx.yoyo.service.ITypeService;
import com.xxxx.yoyo.service.impl.GoodsServiceImpl;
import com.xxxx.yoyo.service.impl.TypeServiceImpl;
import com.xxxx.yoyo.util.PageUtil;

/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/index/search")
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private ITypeService typeService = new TypeServiceImpl();
	private IGoodsService goodsService = new GoodsServiceImpl();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置导航栏 [宠物分类] 被选中
		request.setAttribute("flag", 2);

		// 获取 [宠物分类] 列表
		List<Type> typeList = typeService.getTypeList();
		// 把typeList存入request中, 供/index/goods.jsp使用
		request.setAttribute("typeList", typeList);

		// 让/index/goods.jsp 正文区域显示 "搜索结果" typeid为4的时候, 才会显示"搜索结果"这四个字
		request.setAttribute("typeid", 4);

		// 在获取参数之前设置读取时的编码是UTF-8, 前端传给后台的时候是UTF-8编码, 我们读取也必须用UTF-8编码解读,否则就会乱码
		request.setCharacterEncoding("UTF-8");// 解决读取中文参数乱码

		// 获取前端传递过来的参数
		String keyword = request.getParameter("name");
		String pageStr = request.getParameter("page");
		String sizeStr = request.getParameter("size");

		// 安全起见,可以设置默认值
		keyword = (keyword == null ? "" : keyword);// 如果没有传参数name,我们把查询关键字设置为 ""
		int page = (pageStr == null ? 1 : Integer.parseInt(pageStr));// 如果没有传参数page,设置默认页码是1
		int size = (sizeStr == null ? 16 : Integer.parseInt(sizeStr));// 如果没有传参数size,设置默认条数是16

		// 获取 [搜索结果] 列表
		List<Goods> goodsList = goodsService.getGoodsListByKeyword(keyword, page, size);
		// 把goodsList存入request中, 供/index/goods.jsp使用
		request.setAttribute("goodList", goodsList);

		// 获取查询结果的总条数
		long count = goodsService.getGoodsCountByKeyword(keyword);

		// 分页信息
		String pageInfo = PageUtil.getPageTool(request, count, page, size);
		// 把pageInfo存入request中, 供/index/goods.jsp使用
		request.setAttribute("pageTool", pageInfo);

		// 请求转发, 跳转到/index/goods.jsp页面
		request.getRequestDispatcher("/index/goods.jsp").forward(request, response);
	}

}
